﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vowei.Data.Models;
using Vowei.Data.Helpers;
using Vowei.Core.Models;
using Newtonsoft.Json;
using Vowei.Data;
using Vowei.Core;
using Vowei.Web.Helpers;
using Vowei.Web.Models;
using System.Collections;

namespace Vowei.Web.Controllers
{
    // TODO: 这个类里的Action基本上都可以跟RequirementController里的Action合并。
    public class TaskController : TicketControllerBase<Task>
    {
        public TaskController(IVoweiContext context, IUser user) : base(context, user) { }

        protected override ActionResult DetailsImpl(Guid id)
        {
            var result = base.DetailsImpl(id) as ViewResult;

            ViewData["UpRequirement"] = ((Task)result.Model).GetUpRequirement(Context);

            return result;
        }

        protected override ActionResult EditImpl(Guid? id)
        {
            var ticket = EntityHelpers.GenericGetObjectDetails<Task>(id, Context);
            var milestones = new ArrayList();

            if (ticket.BelongsToMilestone == null)
            {
                var results = from m in Context.Milestones.Query
                              select new { m.ID, m.Title };

                foreach (var item in results)
                {
                    milestones.Add(item);
                }
            }
            else
            {
                var mid = ticket.BelongsToMilestone.ID;
                var project = Context.Milestones.Include("BelongsToMilestone").Query.First(m => m.ID == mid);
                // TODO: 下面这个循环改成一个存储过程吧，要查询数据库几次
                while (project.BelongsToMilestone != null)
                {
                    mid = project.BelongsToMilestone.ID;
                    project = Context.Milestones.Include("BelongsToMilestone").Query.First(m => m.ID == mid);
                }

                // 把项目添加进去
                milestones.Add(project);
                foreach (var item in project.AllMilestones(Context))
                    milestones.Add(item);

                ViewData["ProjectId"] = project.ID;
            }

            ViewData["Milestones"] = ViewHelpers.SerializeToJson(milestones);
            return View("Edit", ticket).AddJsonSupport();
        }

        protected override ActionResult EditImpl(Task task)
        {
            if (task.BelongsToMilestone != null)
                ((IScoped)task).BelongsToMilestone = Context.Milestones.Find(task.BelongsToMilestone.ID);
            else
                throw new InvalidOperationException(string.Format(T("正在尝试新建的需求 {0} 没有指定里程碑！"), task.Title));

            EditingHelpers.GenericEndEdit(task, Context, CurrentUser);

            // TODO: 看看如何把这些小的补丁整合成一个通用的函数
            if (Request != null &&
                Request.AcceptTypes.Any(s => s == "application/json"))
            {
                var json = ViewHelpers.SerializeToJson(new
                {
                    task.ID,
                    task.Title
                });
                Response.Write(json);

                return WebConstants.HttpSuccess;
            }
            else
            {
                return RedirectToAction("Details", new { id = task.ID });
            }
        }

        public ActionResult UnAssigned(Guid pid)
        {
            var project = Context.Projects.Find(pid);
            var tasks = project.UnAssignedTasks(Context);

            return JsonImpl(tasks.OfType<Task>());
        }
    }
}
